import os

from flask import Flask, url_for, request, Response

app = Flask(__name__)


@app.route('/', methods=['GET', 'POST'])
def home():
    html = '<a name="downloadbtn" class="btn btn-success pull-right" href="/downloadfile/?filename=com.app.apk">下载</a>'
    return '<h1>aaa</h1><br>' + html


@app.route('/downloadfile/', methods=['GET', 'POST'])
def downloadfile():
    if request.method == 'GET':
        fullfilename = os.getcwd() +'/'+ request.args.get('filename')
        # fullfilename = '/root/allfile/123.txt'
        fullfilenamelist = fullfilename.split('/')
        filename = fullfilenamelist[-1]
        filepath = fullfilename.replace('/%s' % filename, '')

        # 普通下载
        # response = make_response(send_from_directory(filepath, filename, as_attachment=True))
        # response.headers["Content-Disposition"] = "attachment; filename={}".format(filepath.encode().decode('latin-1'))
        # return send_from_directory(filepath, filename, as_attachment=True)
        # 流式读取
        def send_file():
            store_path = fullfilename
            with open(store_path, 'rb') as targetfile:
                while 1:
                    data = targetfile.read(20 * 1024 * 1024)  # 每次读取20M
                    if not data:
                        break
                    yield data

        response = Response(send_file(), content_type='application/x-zip-compressed')
        response.headers["Content-disposition"] = 'attachment; filename=%s' % filename  # 如果不加上这行代码，导致下图的问题
        return response


if __name__ == "__main__":
    app.run(host='192.168.6.13', port=5000, debug=True)
